// 使用测试机的IP地址，在工具设置中忽略域名校验
const HOST_IP = 'nyjk.up.jd.com';
const UPLOAD_URL = `http://${HOST_IP}:3000/upBigFile`;
const MERGE_URL = `http://${HOST_IP}:3000/mergeBigFile`;
Page({
  data: {
    cameraContext: null,
    isRecording: false,
    segments: [],
    segmentDuration: 4 * 60 * 1000, // 每段5分钟（300000毫秒）
  },

  onLoad: function () {
    this.setData({ cameraContext: wx.createCameraContext() });
  },

  startRecording: function () {
    const context = this.data.cameraContext;
    if (!this.data.isRecording) {
      this.uuid = `${Date.now()}-${Math.floor(Math.random() * 100000000)}`;
      this.index = 0;
      // 初始化分段录制
      this.setData({ isRecording: true, segments: [] });
    }
    // 开始录制
    context.startRecord({
      timeout: 5 * 60,
      success: () => {
        console.log('Recording started');
        wx.setKeepScreenOn({
          keepScreenOn: true,
        });
        this.scheduleSegmentStop();
      },
      fail: (err) => {
        console.error('Start recording failed:', err);
      },
    });
  },

  scheduleSegmentStop: function () {
    if (!this.data.isRecording) return;
    // 定时停止当前段录制
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      this.stopSegmentRecording();
    }, this.data.segmentDuration);
  },

  stopSegmentRecording: function (cb) {
    const context = this.data.cameraContext;
    context.stopRecord({
      success: (res) => {
        // 保存当前段的视频路径
        this.upFile(res.tempVideoPath);
        this.index = this.index + 1;
        if (this.data.isRecording) {
          this.startRecording();
        } else {
          cb && cb(res.tempVideoPath);
        }
      },
      fail: (err) => {
        console.error('Stop recording failed:', err);
      },
    });
  },

  stopRecording: function (e) {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.setData({ isRecording: false }, () => {
      // 录制完成后的处理，例如上传所有视频片段
      this.stopSegmentRecording((url) => {
        this.uploadSegments(url);
      });
    });
  },

  upFile: function (segmentPath, cb) {
    wx.uploadFile({
      url: UPLOAD_URL, // 服务器上传接口
      filePath: segmentPath,
      name: 'file',
      formData: {
        identifier: this.uuid,
        index: this.index,
      },
      header: { 'Content-type': 'multipart/form-data' },
      success: () => {
        console.log(segmentPath);
        this.setData({ segments: [...this.data.segments, segmentPath] }, () => {
          cb && cb();
        });
      },
      fail: (e) => {
        console.log(e, 2222);
      },
    });
  },

  uploadSegments: function (url) {
    this.upFile(url, () => {
      wx.setKeepScreenOn({ keepScreenOn: false });
      console.log('上传完成，开始合并', this.data.segments.length, this.index);
      wx.request({
        url: `${MERGE_URL}?identifier=${this.uuid}`,
        method: 'GET',
        timeout: 300000,
        success: (res) => {
          console.log(res, '【成功】');
        },
        fail: (res) => {
          console.log(res, '【失败】');
        },
      });
    });
  },
});
